由一個條件句去判斷 bool 值,若是true就執行 statement,false就跳過。
if(boolean_expression)
{
   /* statement(s) will execute if the boolean expression is true */
}

跟上面很像,就差在else,在 bool值為false時會執行 statement2。
if(boolean_expression)
{
   /* statement1(s) will execute if the boolean expression is true */
}
else
{
  /* statement2(s) will execute if the boolean expression is false */
}

ex.
int main() {
    
    int a = 100;
    
    if (a < 20) {
        NSLog(@"a 小於 20");
    } else {
        NSLog(@"a 大於 20");
    }
    
    NSLog(@"value of a is : %d",a);
    return 0;
}
結果:
2021-09-15 17:39:42.936729+0800 TestOC[81516:975631] a 大於 20
2021-09-15 17:39:42.937428+0800 TestOC[81516:975631] value of a is : 100
可以用來測試各種條件。
當使用 if , else if , else 語句時,有幾點要牢記:
if(boolean_expression 1)
{
   /* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
   /* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
   /* Executes when the boolean expression 3 is true */
}
else 
{
   /* executes when the none of the above condition is true */
}
ex.
#import <Foundation/Foundation.h>
int main() {
    
    int a = 20;
    
    if (a == 10) {
        NSLog(@"a 等於 10");
    } else if (a == 20){
        NSLog(@"a 等於 20");
    } else if (a == 30){
        NSLog(@"a 等於 30");
    } else {
        NSLog(@"value of a is : %d",a);
    }
    return 0;
}
與 if 語句不同的地方在於,if 主要判斷條件的對錯(bool值),只會有兩種情況(true, false) ; 而 switch 則可以有許多情況,可用於多種可能。
switch(expression){
    case constant-expression  :
       statement(s);
       break; /* optional */
    case constant-expression  :
       statement(s);
       break; /* optional */
  
    /* you can have any number of case statements */
    default : /* Optional */
       statement(s);
}

ex.
#import <Foundation/Foundation.h>
int main() {
    
    char grade = 'B';
    
    switch (grade) {
        case 'A' :
            NSLog(@"Excellent!");
            break;
        
		case 'B' :
        case 'C' :
            NSLog(@"Well done");
            break;
        case 'D' :
            NSLog(@"You passed");
            break;
        case 'F' :
            NSLog(@"Better try again");
            break;
        default :
            NSLog(@"Invalid grade");
    }
    NSLog(@"Your grade is  %c", grade);
    
    return 0;
}
結果:
2021-09-15 18:09:25.397015+0800 TestOC[81888:995326] Well done
2021-09-15 18:09:25.397875+0800 TestOC[81888:995326] Your grade is  B
可以用來代替 if...else 語句
Bool ? Exp2 : Exp3;
如果 Bool 為true,會跑到 Exp2。反之,為false,會跑到 Exp3。